/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.pay.handler.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.bblocks.enums.SysEnum;
import com.bblocks.exception.ServiceException;
import com.bblocks.util.ServletUtils;
import com.ijpay.alipay.AliPayApiConfigKit;
import com.pig4cloud.pigx.pay.entity.DTO.PayParamsDTO;
import com.pig4cloud.pigx.pay.entity.PayChannel;
import com.pig4cloud.pigx.pay.entity.PayTradeOrder;
import com.pig4cloud.pigx.pay.handler.PayOrderHandler;
import com.pig4cloud.pigx.pay.utils.ChannelPayApiConfigKit;
import com.pig4cloud.pigx.pay.utils.ExtraParamsEnum;
import com.pig4cloud.pigx.pay.utils.OrderStatusEnum;
import com.pig4cloud.pigx.pay.utils.PayChannelNameEnum;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

/**
 * @author lengleng
 * @date 2019-05-31
 */
public abstract class AbstractPayOrderHandler implements PayOrderHandler {

	public Object handle(PayParamsDTO goodsOrde){
		throw new ServiceException(SysEnum.ERR_NO_REALIZE);
	}

	public PayTradeOrder handlePay(PayParamsDTO payInfo) throws IOException {
		PayChannel payChannel = preparePayParams(payInfo.getTenantId());
		ChannelPayApiConfigKit.put(payChannel);

		PayTradeOrder tradeOrder  = null;
		try {
			tradeOrder = this.createTradeOrderIfNull(payInfo);
			if (!OrderStatusEnum.INIT.getStatus().equals(tradeOrder.getStatus())) {
				throw new ServiceException(SysEnum.PAY_ERROR.getCode(), "支付单状态非法！");
			}

			Object result = pay(tradeOrder);
			if(result != null)
				tradeOrder.setPayInfo(result);
		}finally {
			// 情况ttl
			ChannelPayApiConfigKit.remove();
		}
		return tradeOrder;
	}




	protected PayTradeOrder setTradeOrderBase(PayParamsDTO payInfo){

		PayTradeOrder tradeOrder = new PayTradeOrder();
		tradeOrder.setAmount(payInfo.getAmount());
		tradeOrder.setChannelId(payInfo.getChannelId());
		tradeOrder.setChannelMchId(AliPayApiConfigKit.getAliPayApiConfig().getAppId());
		tradeOrder.setClientIp(ServletUtil.getClientIP(ServletUtils.getRequest()));
		tradeOrder.setCurrency("cny");
		tradeOrder.setExpireTime(30L);
		tradeOrder.setStatus(OrderStatusEnum.INIT.getStatus());
		tradeOrder.setSubject(payInfo.getSubject());

		tradeOrder.setBody(StrUtil.isNotEmpty(payInfo.getBody())? payInfo.getBody() : payInfo.getSubject());

		tradeOrder.setTenantId(null);
		tradeOrder.setReqNo(payInfo.getReqNo());
		tradeOrder.setPayType(payInfo.getPayType());

		if(StrUtil.isNotEmpty(payInfo.getReqChn())){
			tradeOrder.setReqChn(payInfo.getReqChn());
		}

		return tradeOrder;
	}

	/**
	 * 组织附加参数，以tenantId=1&channelId=2形式
	 * 参数值为空则抛弃
	 * @param tenantId
	 * @param channelId
	 * @return
	 */
	protected String formExtraParams(Long tenantId,String channelId){
		StringBuilder result = new StringBuilder();
		if(StrUtil.isNotEmpty(channelId))
			result.append(ExtraParamsEnum.CHANNEL_ID.getName() + "=" + channelId);

		if(tenantId != null && tenantId > 0L) {
			if(result.length() > 0)
				result.append("&");
			result.append(ExtraParamsEnum.TENANT_ID.getName() + "=" + tenantId);
		}

		return result.toString();
	}
}
